package cn.jekun.shop.common.service;

import java.sql.Types;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import cn.jekun.component.base.bean.ErrorMsg;
import cn.jekun.component.base.bean.Page;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.MD5;
import cn.jekun.component.base.validator.annotation.Mobile;
import cn.jekun.component.base.validator.annotation.RegExp;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.RsSms;
import cn.jekun.component.core.bean.gen.RsUser;
import cn.jekun.component.core.service.SMSService;
import cn.jekun.component.core.service.ScmService;
import cn.jekun.component.core.service.gen.RsSmsService;
import cn.jekun.component.core.service.gen.RsUserService;
import cn.jekun.shop.web.bean.User;
@Service(ForgetPwdService.BEAN_NAME)
public class ForgetPwdService extends ShopBaseService{
	public static final String BEAN_NAME = "cn.jekun.shop.common.ForgetPwd";
	public static final String NAMESPACE = "SHOP_MEMBER_USER";
	@Override
	public String getNamespace() {
		return NAMESPACE;
	}
	@Resource(name = RsSmsService.BEAN_NAME)
	RsSmsService rsSmsService;
	@Resource(name=RsUserService.BEAN_NAME)
	RsUserService userService;
	@Resource(name = ScmService.BEAN_NAME)
	private ScmService scmService;
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JSONObject getForgetPwdValidateCode(
			@Mobile(message="手机号非法")
			String mobile){
		Map formMap = new HashMap();
		JSONObject jsonObject = new JSONObject();
		/*if (StringUtils.isBlank(mobile)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"手机不能为空");
		}*/
		formMap.put(RsUser.COL_MOBILE, mobile);
		SqlUtis.prepareSql(formMap, "", SqlUtis.getSQL(formMap, "a."
				+ RsUser.COL_MOBILE, Types.VARCHAR, SqlUtis.EQ));
		boolean flag = rsUserService.exists(formMap);
		if (!flag) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"此用户不存在");
		}else{
			SMSService.checkTime(mobile);//检查发送间隔
			//一天最多5条
			if(!this.smsService.checkOverTimes(mobile, 	Constants.RS_SMS_TYPE.RE_LOGIN_PWD, "24", 5)){
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
						"一天最多5条,请稍后再操作");
			}
			//发送忘记密码的手机验证码
			try {
				// 生成随机类
				Random random = new Random();
				// 取随机产生的认证码(4位数字)
				String sRand = "";
				for (int i = 0; i < 6; i++) {
					String rand = String.valueOf(random.nextInt(10));
					sRand += rand;
				}
				String content = "您正在找回登录密码，验证码"+sRand+"，请在页面填写，如非本人操作，请忽略。" ;
//				// 将认证码存入数据库
//				Map insertMap = new HashMap();
//				RsSms rsSms = new RsSms();
//				rsSms.setContent(content);
//				rsSms.setMemo(sRand);
//				rsSms.setMobile(mobile);
//				rsSms.setSmsTypeId(Constants.RS_SMS_TYPE.RE_LOGIN_PWD);// 找回登录密码验证码
//				insertMap.put("rsSms", rsSms);
//				rsSmsService.insert(insertMap);
				// 发送短信
				String error = this.smsService.sendSMS(mobile, content, Constants.RS_SMS_TYPE.RE_LOGIN_PWD, sRand);
				if (error != null) {
					jsonObject.put(ErrorMsg.KEY_MESSAGE, error);
					return this.executeRerutnFail(jsonObject);
				}
				return this.executeRerutn(jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
				return this.executeRerutnFail(jsonObject);
			}
		}
	}
	/**
	 * 
	 * @param mobile
	 * @param validateCode
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JSONObject checkValidateCode(
			@Mobile(message="手机号非法")
			String mobile, 
			@RegExp(regExp="^[0-9]{6}$",message="验证码必须为6为数字")
			String validateCode) {
		if (StringUtils.isBlank(mobile)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"手机号码不能为空");
		}
		if (StringUtils.isBlank(validateCode)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"短信验证码不为空");
		}
		JSONObject jsonObject = new JSONObject();
		// 短信验证码验证（查找最新的短信信息验证码）
		String tempCode = null;// 手机验证码
		Map tempSmsMap = new HashMap();
		tempSmsMap.put(RsSms.COL_MOBILE, mobile);
		tempSmsMap.put(RsSms.COL_SMS_TYPE_ID, Constants.RS_SMS_TYPE.RE_LOGIN_PWD);
		SqlUtis.prepareSql(tempSmsMap, "", 
				SqlUtis.getSQL(tempSmsMap, "a."+ RsSms.COL_MOBILE, Types.VARCHAR, SqlUtis.EQ),
				SqlUtis.getSQL(tempSmsMap, "a."+ RsSms.COL_SMS_TYPE_ID, Types.VARCHAR, SqlUtis.EQ), SqlUtis
				.orderBy(" a.create_time desc nulls last"));
		Page smsPage = new Page();
		smsPage.setPageSize(1);
		List<RsSms> smsList = this.rsSmsService.list(tempSmsMap, smsPage);
		if (smsList != null && smsList.size() == 1) {
			RsSms rsSms = smsList.get(0);
			tempCode = rsSms.getMemo();
		}
		if (!validateCode.equals(tempCode)) {
			throw new BusinessException("-3210",
					"验证码错误");
		}
		return executeRerutn(jsonObject);
	}
	/**
	 * 
	 * @param mobile
	 * @param newPwd
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public JSONObject resetLoginPwd(
			@Mobile(message="手机号非法")
			String mobile, 
			@MD5(message="密码未加密")
			String newPwd) {
		if (StringUtils.isBlank(mobile)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"手机号码不能为空");
		}
		if (StringUtils.isBlank(newPwd)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
					"密码不能为空");
		}
		JSONObject jsonObject = new JSONObject();
		newPwd = this.versionCompatible(newPwd);
		try {
			Map tempUserMap = new HashMap();
			tempUserMap.put(User.COL_MOBILE, mobile);
			SqlUtis.prepareSql(tempUserMap, "", SqlUtis.getSQL(tempUserMap, "b."
					+ User.COL_MOBILE, Types.VARCHAR, SqlUtis.EQ));
			User rsUser = this.one(tempUserMap);
			if (rsUser == null) {
				throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,
						"用户不存在");
			}else{	
				Map map = new HashMap();
				RsUser user = new RsUser();
				map.put("rsUser", user);
				map.put(RsUser.COL_USER_ID, rsUser.getUserId());
				user.setPassword(newPwd);
				user.setResetPassword("");
				SqlUtis.prepareSql(map
						, SqlUtis.getSQLRequired(map,"a."+RsUser.COL_USER_ID,Types.VARCHAR,SqlUtis.EQ));
				this.userService.update(map);
				
				//同步开店用户到scm系统
		    	RsUser tempUser = this.rsUserService.one(rsUser.getUserId());
		    	
		    	//判断当前操作人是否为店长角色
		    	
		    	if(this.scmService.isSJ(rsUser.getUserId())){
		    		boolean flag = this.scmService.synDataToScm(tempUser);
		    		if(!flag){
		    			log.info("#######用户数据到SCM同步失败#########");
		    		}else{
		    			log.info("#######用户数据到SCM同步成功#########");
		    		}
		    		
		    	}
				
				return executeRerutn(jsonObject);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return this.executeRerutnFail(jsonObject);
		}
	}
}
